'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 改名
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var Code = require('../../../consts/code');
var moduleType = require('../../../consts/moduleType');
var operationType = require('../../../consts/operationType');
var PlayerManager = require('../../../libs/playerManager');
var filterSensitiveService = require('../../../services/filterSensitiveService');
var roleService = require('../../../services/roleService');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

/**
 * 改名字
 */
Handler.prototype.change = function (msg, session, next) {
    var role_id = session.uid;
    var name = msg.name;
    if (!name) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['role', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var role_model = player_manager.role;

                // 检测名字是否含有敏感词
                if (!filterSensitiveService.detect(name)) {
                    return next(null, {
                        code: Code.ROLE_NAME_CONTAIN_SENSITIVE
                    });
                }

                // 判断是否包含特殊符号
                if (_containtInvalidChar(name)) {
                    return next(null, {
                        code: Code.ROLE_NAME_CONTAIN_INVALID_CHAR
                    });
                }

                // 扣除钻石
                // todo: 未配置暂定100钻石
                if (!roleService.subDiamond(player_manager, moduleType.MDL_OTHER, operationType.OPR_OTHER_RENAME_ROLE, 100)) {
                    return next(null, {
                        code: Code.USER_DIAMOND_NOT_ENOUGH
                    });
                }

                role_model.setName(name);
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK
            });
        }
    );
};

/**
 * 判断角色名是否包含无效符号
 * @param  {[type]} role_id [description]
 * @return {[type]}         [description]
 */
var _containtInvalidChar = function (name) {
    var cr = String.fromCharCode(13);
    var cn = String.fromCharCode(10);
    return (name.indexOf(cr) >= 0) || (name.indexOf(cn) >= 0);
};
